package com.aiyige.utils;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;

import java.util.LinkedList;
import java.util.List;

/**
 * Created by zhuyakun on 2018/2/9.
 */

public class PermissionUtil {
    public static List<String> pickUngrantedPremission(Activity activity, String... permissions) {
        List<String> unGrantedPermissionList = new LinkedList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {//当目标sdk低于23时checkSelfPermission始终返回0
                    unGrantedPermissionList.add(permission);
                }
            }
        }
        return unGrantedPermissionList;
    }

    public static List<String> batchConvertPermissionToReadableString(Activity activity, List<String> permissionList) {
        List<String> nameList = new LinkedList<>();
        for (String permission : permissionList) {
            String name = convertPermissionToReadableString(activity, permission);
            if (!TextUtils.isEmpty(name)) {
                nameList.add(name);
            }
        }
        return nameList;
    }

    public static String convertPermissionToReadableString(Activity activity, String permission) {
        PackageManager packageManager = activity.getPackageManager();
        try {
            return packageManager.getPermissionInfo(permission, PackageManager.GET_META_DATA).loadLabel(packageManager).toString();
        } catch (PackageManager.NameNotFoundException e) {
            return "";
        }
    }


}